<?php
class BaseAction extends Action
{
    private $_city = 0;
    private $_cityName = '';
    private $_config = array();

    public function _initialize()
    {
        //设置网站默认地址
        //if(!Cookie::get('home')){
        // 		Cookie::set('home', '320100');
        //}
        //$this->_city = Cookie::get('home');
        $this->_city = 320100;
        $this->_cityName = '南京';
        $this->loadDefaultConfig();
        $this->loadLoginUser();
    }

    /**
     * 加载登陆用户信息
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function loadLoginUser()
    {
        $uid = getLoginUserInfo();
        if ($uid) {
            setOnline($uid);
            $userInfo = M('Users')->find($uid);
            $this->assign('userInfo', $userInfo);
            $this->assign('uid', intval($uid));
        }
    }

    /**
     * 获取当前城市
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getCity()
    {
        return $this->_city;
    }

    /**
     * 当前城市名称
     * @return string
     */
    public function getCityName()
    {
        return $this->_cityName;
    }

    /**
     * 获取网站配置
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getConfig()
    {
        return $this->_config;
    }

    /**
     * 加载默认参数
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function loadDefaultConfig()
    {
        $cityName = $this->getCityName();
        $this->assign('web_title', $cityName . '打折网-摩客网-专业商场打折信息提供商');
        $this->assign('web_keywords', $cityName . '打折网,' . $cityName . '商场活动,' . $cityName . '商场打折信息');
        $this->assign('web_description', '摩客网为用户提供最及时、详细、准确的南京商场打折信息及南京商场活动。 ');
    }

    /**
     * 重新设置参数
     * @param String $key 键
     * @param Mixed $value 值
     * @param Boolea $isOverlap 是否覆盖
     * @param String $partition 分隔符
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function reset($key, $value, $isOverlap = false, $partition = '-')
    {
        if ($key == 'web_keywords') {
            $partition = ',';
        }
        $data = $this->__get($key);
        if ($isOverlap) {
            $data = '';
        }
        if (is_string($value)) {
            if ($isOverlap) {
                $data = $value;
            } else {
                $data = $value . $partition . $data;
            }
        } else if (is_array($value)) {

            foreach ($value as $v) {
                $data = $v . $partition . $data;
            }
        }
        $this->assign($key, $data);
        return $data;
    }

    /**
     * 真对页面seo优化设置
     * @param String $title 标题
     * @param String $keywords 关键字
     * @param String $description 描述
     * @param Blooea $isOverTitle 是否覆盖标题
     * @param Blooea $isOverKeyWords 是否覆盖关键字
     * @param Blooea $isOverDescription 是否覆盖描述
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function seoSet($title, $keywords = null, $description = null, $isOverTitle = false, $isOverKeyWords = false, $isOverDescription = true)
    {
        $this->reset('web_title', $title, $isOverTitle);
        if (!empty($keywords)) {
            $this->reset('web_keywords', $keywords, $isOverKeyWords);
        }
        if (!empty($description)) {
            $this->reset('web_description', $description, $isOverDescription);
        }
    }

    /**
     * 设置商场seo
     * @param String $name 名称
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function mallSeoSet($name)
    {
        $cityName = $this->getCityName();
        $this->reset('web_title', $cityName . $name . '-' . $name . '活动-摩客网', true);
        $this->reset('web_keywords', $name . ',' . $cityName . $name, true);
        $this->reset('web_description', $cityName . $name . '的商场活动每天都将更新，' . $cityName . $name . '的打折信息精准到柜台，请和您的朋友分享在' . $cityName . $name . '购物的乐趣。', true);
    }

    /**
     * 调用命令行方法接口
     * @param string $name
     * @return Action, boolean
     */
    public function cliA($name)
    {
        return A('cli://' . $name);
    }

    /**
     * 获取IP地址
     * @param string $ip
     * @return array
     */
    public function getIpDetail($ip = null)
    {
        if (!isset($ip)) {
            $ip = get_client_ip();
        }
        $IpModel = M('Ip');
        $ipDetail = $IpModel->field('detail, view_count')->find($ip);
        if ($ipDetail) {
            $data = array();
            $data['ip'] = $ip;
            $data['view_count'] = $ipDetail['view_count'] + 1;
            $IpModel->save($data);
            return json_decode($ipDetail['detail']);
        } else {
            $ipDetail = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);
            if ($ipDetail) {
                $ipArray = json_decode($ipDetail);
                if ($ipArray->code == 0) {
                    $data = array();
                    $data['ip'] = $ip;
                    $data['detail'] = $ipDetail;
                    $IpModel->add($data);
                    return json_decode($ipDetail);
                }
            }
            return null;
        }
        return json_decode($ipDetail);
    }

    /**
     * 获取缓存
     * @param string $name
     * @return mixed
     */
    function getCache($name)
    {
        if (APP_DEBUG) {
            return false;
        } else {
            return S($name);
        }
    }

    /**
     * 设置缓存
     * @param string $name
     * @param mixed  $data
     * @param int $expire
     * @return mixed
     */
    public function setCache($name, $data = null, $expire = 60)
    {
        if (APP_DEBUG) {
            return false;
        } else {
            return S($name, $data, $expire);
        }
    }

    /**
     * 获取城市缓存
     * @param string $name
     * @return mixed
     */
    public function getCityCache($name)
    {
        return $this->getCache($this->getCity() . '-' . $name);
    }

    /**
     * 获取城市缓存
     * @param string $name
     * @param mixed  $data
     * @param int $expire
     * @return mixed
     */
    public function setCityCache($name, $data = null, $expire = 60)
    {
        return $this->setCache($this->getCity() . '-' . $name, $data, $expire);
    }

    /**
     * 获取滚动图
     * @param int $mid
     * @param int $fid
     * @param int $bid
     * @return array
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getSlide($mid = null, $fid = null, $bid = null)
    {
        $cacheName = 'slide-' . intval($mid) . '-' . intval($fid) . '-' . intval($bid);
        $slide = $this->getCache($cacheName);
        if (empty($slide)) {
            $SlideModel = D('Slide');
            if ($mid && !$fid && !$bid) {
                //商场
                $slide = $SlideModel->getMallList($mid);
            } else if ($mid && $fid && $bid) {
                //品牌
            } else {
                $slide = $SlideModel->getIndexList();
            }
            $this->setCache($cacheName, $slide, 60);
        }
        return $slide;
    }

    /**
     * 错误信息利用语言包显示
     * @param string $name
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function errorLang($name)
    {
        $this->error(L($name));
        exit;
    }

    /**
     * 正确信息利用语言包显示
     * @param string $name
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function successLang($name)
    {
        $this->success(L($name));
        exit;
    }

    /**
     * 根据缓存检测商场信息是否正确
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getMallCache()
    {
        $malls = array();
        $malls = $this->getCityCache('mlls-index-ename');
        if (empty($malls)) {
            $map['city'] = $this->getCity();
            $malls = D('Market')->getIndexData($map);
            foreach ($malls as $key => $m) {
                $malls[strtolower($m['initial'])] = $m;
                unset($malls[$key]);
            }
            $this->setCityCache('mlls-index-ename', $malls);
        }
        return $malls;
    }

    /**
     * 根据商场获取楼层缓存信息
     * @param int $mid
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getMallFloorCache($mid)
    {
        $cacheName = 'mlls-floor-list-' . $mid;
        $floors = $this->getCache($cacheName);
        if (empty($floors)) {
            $floors = D('Floor')->getList($mid);
            if ($floors) {
                foreach ($floors as $key => $f) {
                    $floors[strtolower($f['sain'])] = $f;
                    unset($floors[$key]);
                }
            }
            $this->setCache($cacheName, $floors);
        }
        return $floors;
    }

    /**
     * 根据商场楼层品牌获取楼层品牌信息
     * @param int $mid
     * @param int $fid
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getMallFloorBrandCache($mid, $fid)
    {
        $cacheName = 'mlls-floor-brand-list-' . $mid . '-' . $fid;
        $brands = $this->getCache($cacheName);
        if (empty($brands)) {
            $brands = D('FloorBrand')->getList($mid, $fid);
            $BrandModel = D('Brand');
            if ($brands) {
                foreach ($brands as $key => $b) {
                    $brand = $BrandModel->getOneLine($b['bid']);
                    if ($brand) {
                        $brands[strtolower($brand['ename'])] = $brand;
                    }
                    unset($brands[$key]);
                }
            }
            $this->setCache($cacheName, $brands);
        }
        return $brands;
    }

    /**
     * 检查URL是否争取
     * @param string $mname
     * @param string $fname
     * @param string $bname
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function checkUrl($mname, $fname = null, $bname = null)
    {
        $this->assign('jumpUrl', U('/'));
        $data = array();
        $floor = null;
        $malls = $this->getMallCache();
        $mall = $malls[$mname];
        if ($mall) {
            $data['mall'] = $mall;
            $data['level'] = 1;
        } else {
            $this->error(L('_MALL_NAME_ERROR_'));
        }
        if ($fname) {
            //商场楼层
            $floors = $this->getMallFloorCache($mall['id']);
            $floor = $floors[$fname];
            if ($floor) {
                $data['floor'] = $floor;
                $data['level'] = 2;
            } else {
                $this->error(L('_MALL_FLOOR_NAME_ERROR_'));
            }
        }
        if ($bname) {
            $brands = $this->getMallFloorBrandCache($mall['id'], $floor['id']);
            if ($brands[$bname]) {
                $data['brand'] = $brands[$bname];
                $data['level'] = 3;
            } else {
                $this->errorLang('_MALL_FLOOR_BRAND_NAME_ERROR_');
            }
        }
        return $data;
    }

    /**
     * 邮件发送
     * @param string/array $users
     * @param array $title
     * @param array $body
     * @param striong $dir
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function sendMail($users, $title, $body, $dir)
    {
        Vendor('PHPMailer.SendMail');
        $mail = new SendMail();
        $mailDir = APP_PATH . '/Mail/' . $dir;
        $ViewTitle = Think::instance('View');
        $ViewBody = Think::instance('View');
        $ViewTitle->assign($title);
        $ViewBody->assign($body);
        $title = $ViewTitle->fetch($mailDir . '/title.html');
        $body = $ViewBody->fetch($mailDir . '/body.html');
        return $mail->setParameAndSend($title, $body, $users);
    }

    /**
     * 自动表单令牌验证
     *
     * @param array $data
     * @return null or boolean
     * @author ice<iceinto@mallog.com.cn>
     */
    public function autoCheckToken($data = null)
    {
        if ($data == null) {
            $data = $_POST;
        }
        $rs = M('')->autoCheckToken($data);
        if ($rs) {
            return true;
        } else {
            $this->errorLang('_TOKEN_ERROR_');
        }
    }

    /**
     * 使用正则验证数据
     * @access public
     * @param string $value  要验证的数据
     * @param string $rule 验证规则
     * @return boolean
     */
    public function regex($value, $rule)
    {
        $validate = array(
            'require' => '/.+/',
            'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
            'url' => '/^http|https:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
            'currency' => '/^\d+(\.\d+)?$/',
            'number' => '/^\d+$/',
            'zip' => '/^\d{6}$/',
            'integer' => '/^[-\+]?\d+$/',
            'double' => '/^[-\+]?\d+(\.\d+)?$/',
            'english' => '/^[A-Za-z]+$/',
        );
        // 检查是否有内置的正则表达式
        if (isset($validate[strtolower($rule)]))
            $rule = $validate[strtolower($rule)];
        return preg_match($rule, $value) === 1;
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param string $message 错误信息
     * @param Boolean $ajax 是否为Ajax方式
     * @return void
     */
    protected function errorSendMail($message, $ajax = false)
    {
        Vendor('PHPMailer.SendMail');
        $mail = new SendMail();
        $mailTitle = '摩客前端操作错误！' . date('Y-m-d G:i:s');
        $mailBody = $mailTitle . '<hr/>' . 'GROUP_NAME: ' . GROUP_NAME .
            '<br/>MODULE_NAME: ' . MODULE_NAME . '<br/>ACTION_NAME: ' . ACTION_NAME .
            '<br/>错误信息：' . $message;
        $mail->setParameAndSend($mailTitle, $mailBody, 'iceinto@163.com');
        parent::error($message, $ajax);
    }

    /**
     *  首页获取最新打折信息
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getCityBus()
    {
        $bus = $this->getCityCache('home-bus');
        if (empty($bus)) {
            $bus = D('Bus')->getBusByCity($this->getCity());
            $this->setCityCache('home-bus', $bus, 60);
        }
        return $bus;
    }

    /**
     * 获取登陆用户详细
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getLoginUserInfo($field = 'id,name')
    {
        $uid = getLoginUserInfo();
        if ($uid) {
            //获取用户名
            $user = M('Users')->field($field)->find($uid);
            //获取积分
            $credit = D('CreditUser')->getUserNum($uid, 1);
            $user['credit'] = intval($credit['num']);
            //获取关注商场数
            $user['att_market'] = intval(D('MarketAttention')->getUserAttCount($uid));
            //获取关注品牌数
            $user['att_brand'] = intval(D('BrandAttention')->getUserAttCount($uid));
            return $user;
        } else {
            return false;
        }
    }

    /**
     * 根据品牌标示获取推荐品牌
     * @param $bid
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getSimilarBrandById($bid, $count = 6)
    {
        $cacheName = 'brand-similar-' . $bid;
        $brands = $this->getCache($cacheName);
        if (empty($brands)) {
            $BrandModel = D('Brand');
            //获取品牌类型
            $brand = $BrandModel->field('pid')->find($bid);
            $brands = $BrandModel->getSimilar($brand['pid'], $count);
            $this->setCache($cacheName, $brands);
        }
        return $brands;
    }

    /**
     * 热门积分兑换
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getHotCredit()
    {
        $cacheName = 'limited-hot';
        $limitedHot = $this->getCityCache($cacheName);
        if (empty($limitedHot)) {
            $limitedHot = D('Limited')->getHot();
            $this->setCityCache($cacheName, $limitedHot);
        }
        return $limitedHot;
    }

    /**
     * 热门特卖
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getHotMallDis()
    {
        $cacheName = 'mall-discount-hot';
        $mallDiscountHot = $this->getCityCache($cacheName);
        if (empty($mallDiscountHot)) {
            $mallDiscountHot = D('MallDiscount')->getHot();
            $this->setCityCache($cacheName, $mallDiscountHot);
        }
        return $mallDiscountHot;
    }

    /**
     * 获取分页信息
     * @param Int $count 总条数
     * @return class Page
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getPage($count, $pageSize = 20)
    {
        return new Page($count, $pageSize);
    }

    /**
     * 返回当天开始时间时间戳
     * @return int
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getThisDayTime()
    {
        $date = new Date();
        $dayTime = $date->format('%Y-%m-%d');
        return strtotime($dayTime);
    }

    public function getMallDis()
    {
        $cacheName = 'home-mall-discount';
        $mallDis = $this->getCityCache($cacheName);
        if (empty($mallDis)) {
            $mallDis = D('MallDiscount')->getCityMallDis();
            $this->setCityCache($cacheName, $mallDis, 60);
        }
        return $mallDis;
    }
}